package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.changgou.canal.util.CanalUtils;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * @Author: HuangFu
 * @Date: 2020/1/31 11:58
 * @Description: 商品监听服务
 */
@CanalEventListener //设置Canal监听
public class GoodsListener {

    private final static String IS_MARKETABLE = "is_marketable";
    private final static String STATUS = "status";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *  商品状态监听
     * @param entryType 当前操作数据库的类型
     * @param rowData  当前操作的数据行
     */
    @ListenPoint(schema = "changgou_goods" , table = "tb_spu")
    public void goodsStatus(CanalEntry.EntryType entryType, CanalEntry.RowData rowData){

        //获取修改之前数据
        Map<String, String> beforeMap = CanalUtils.convertToMap(rowData.getBeforeColumnsList());
        //获取修改之后
        Map<String, String> afterMap = CanalUtils.convertToMap(rowData.getAfterColumnsList());

        //获取上下架状态修改之前数据
        String beforeMarketable = beforeMap.get(IS_MARKETABLE);
        //获取上下架状态修改之后数据
        String afterMarketable = afterMap.get(IS_MARKETABLE);
        //判断修改之后状态为下架，修改之前为上架状态 0->1
        if("0".equals(beforeMarketable) && "1".equals(afterMarketable)){
            //发送修改数据的ID
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",afterMap.get("id"));
        }

        //判断修改之后状态为上架，修改之前为下架状态 0->1
        if("1".equals(beforeMarketable) && "0".equals(afterMarketable)){
            //发送修改数据的ID
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",afterMap.get("id"));
        }

        //获取商品审核状态之前
        String beforeStatus = beforeMap.get(STATUS);
        //获取商品审核状态之后
        String afterStatus = afterMap.get(STATUS);
        //审核状态从0变1
        if("0".equals(beforeStatus)&&"1".equals(afterStatus)){
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",afterMap.get("id"));
        }

    }

}
